package com.dhcc.DRGsHosp.facade.impl;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.inject.Named;

import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.dayatang.utils.Page;
import org.openkoala.koala.commons.InvokeResult;
import org.openkoala.security.shiro.CurrentUser;
import org.springframework.beans.factory.annotation.Autowired;

import com.dhcc.DRGsHosp.application.DailyRecordApplication;
import com.dhcc.DRGsHosp.application.DepartmentApplication;
import com.dhcc.DRGsHosp.core.domain.DailyRecord;
import com.dhcc.DRGsHosp.core.domain.Department;
import com.dhcc.DRGsHosp.facade.DailyRecordFacade;
import com.dhcc.DRGsHosp.facade.DayMonitorFacade;
import com.dhcc.DRGsHosp.facade.DrgsIndexCalFacade;
import com.dhcc.DRGsHosp.facade.dto.DailyRecordDTO;
import com.dhcc.DRGsHosp.facade.dto.DepShowDTO;
import com.dhcc.DRGsHosp.facade.dto.IndexCalDTO;
import com.dhcc.DRGsHosp.facade.impl.assembler.DailyRecordAssembler;
import com.dhcc.DRGsHosp.infra.util.DrgsIndex;
import com.dhcc.DRGsHosp.infra.util.GlobalData;
import com.dhcc.DRGsHosp.infra.util.StringUtils;
/**
 * 
 * @ClassName: DailyRecordFacadeImpl  
 * @Description ：    病例日监测
 * @Date: 2017年6月19日 上午7:26:39  
 * @Author LiuHongJun 
 * @Version 2.5.0 DHC-DRGs
 */
@Named("drgsHospFacadeImpl3")
public class DailyRecordFacadeImpl implements DailyRecordFacade {

	@Autowired
	private DailyRecordApplication  application;
	
	@Autowired
	private DepartmentApplication departmentApplication;
	
	@Autowired
	private DayMonitorFacade dayMonitorFacade;
	
	@Autowired
	private DrgsIndexCalFacade drgsIndexCalFacade;
	
	@Autowired 
	private JdbcTemplateObj jdbcTemplateObj;
	
	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
	
	public InvokeResult getDailyRecord(String drEpisodeid) {
		return InvokeResult.success(DailyRecordAssembler.toDTO(application.getDailyRecord(drEpisodeid)));
	}
	
	public InvokeResult creatDailyRecord(DailyRecordDTO dailyRecordDTO) {
		application.creatDailyRecord(DailyRecordAssembler.toEntity(dailyRecordDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult updateDailyRecord(DailyRecordDTO dailyRecordDTO) {
		application.updateDailyRecord(DailyRecordAssembler.toEntity(dailyRecordDTO));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDailyRecord(String drEpisodeid) {
		application.removeDailyRecord(application.getDailyRecord(drEpisodeid));
		return InvokeResult.success();
	}
	
	public InvokeResult removeDailyRecords(String[] drEpisodeids) {
		Set<DailyRecord> dailyRecords= new HashSet<DailyRecord>();
		for (String drEpisodeid : drEpisodeids) {
			dailyRecords.add(application.getDailyRecord(drEpisodeid));
		}
		application.removeDailyRecords(dailyRecords);
		return InvokeResult.success();
	}
	
	public List<DailyRecordDTO> findAllDailyRecord() {
		return DailyRecordAssembler.toDTOs(application.findAllDailyRecord());
	}
	
	public Page<DailyRecordDTO> pageQueryDailyRecord(DailyRecordDTO queryVo, int currentPage, int pageSize) {
		List<Object> conditionVals = new ArrayList<Object>();
	   	StringBuilder jpql = new StringBuilder("select _dailyRecord from DailyRecord _dailyRecord   where 1=1 ");
	   	if (queryVo.getDrEpisodeid() != null && !"".equals(queryVo.getDrEpisodeid())) {
	   		jpql.append(" and _dailyRecord.drEpisodeid like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrEpisodeid()));
	   	}		
	   	if (queryVo.getDrMrno() != null && !"".equals(queryVo.getDrMrno())) {
	   		jpql.append(" and _dailyRecord.drMrno like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrMrno()));
	   	}		
	   	if (queryVo.getDrPatientname() != null && !"".equals(queryVo.getDrPatientname())) {
	   		jpql.append(" and _dailyRecord.drPatientname like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrPatientname()));
	   	}		
	   	if (queryVo.getDrIndate() != null) {
	   		jpql.append(" and _dailyRecord.drIndate between ? and ? ");
	   		conditionVals.add(queryVo.getDrIndate());
	   		conditionVals.add(queryVo.getDrIndateEnd());
	   	}	
	   	if (queryVo.getDrOutdate() != null) {
	   		jpql.append(" and _dailyRecord.drOutdate between ? and ? ");
	   		conditionVals.add(queryVo.getDrOutdate());
	   		conditionVals.add(queryVo.getDrOutdateEnd());
	   	}	
	   	if (queryVo.getDrPatienttype() != null && !"".equals(queryVo.getDrPatienttype())) {
	   		jpql.append(" and _dailyRecord.drPatienttype like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrPatienttype()));
	   	}		
	   	if (queryVo.getDrIndep() != null && !"".equals(queryVo.getDrIndep())) {
	   		jpql.append(" and _dailyRecord.drIndep like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrIndep()));
	   	}		
	   	if (queryVo.getDrOutdep() != null && !"".equals(queryVo.getDrOutdep())) {
	   		jpql.append(" and _dailyRecord.drOutdep like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrOutdep()));
	   	}		
	   	if (queryVo.getDrDrugcost() != null) {
	   		jpql.append(" and _dailyRecord.drDrugcost=?");
	   		conditionVals.add(queryVo.getDrDrugcost());
	   	}	
	   	if (queryVo.getDrNodrugcost() != null) {
	   		jpql.append(" and _dailyRecord.drNodrugcost=?");
	   		conditionVals.add(queryVo.getDrNodrugcost());
	   	}	
	   	if (queryVo.getDrTotalcost() != null) {
	   		jpql.append(" and _dailyRecord.drTotalcost=?");
	   		conditionVals.add(queryVo.getDrTotalcost());
	   	}	
	   	if (queryVo.getDrIsabnormal() != null) {
	   		jpql.append(" and _dailyRecord.drIsabnormal=?");
	   		conditionVals.add(queryVo.getDrIsabnormal());
	   	}	
	   	if (queryVo.getDrInhisdep() != null && !"".equals(queryVo.getDrInhisdep())) {
	   		jpql.append(" and _dailyRecord.drInhisdep like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrInhisdep()));
	   	}		
	   	if (queryVo.getDrOuthisdep() != null && !"".equals(queryVo.getDrOuthisdep())) {
	   		jpql.append(" and _dailyRecord.drOuthisdep like ?");
	   		conditionVals.add(MessageFormat.format("%{0}%", queryVo.getDrOuthisdep()));
	   	}		
        Page<DailyRecord> pages = getQueryChannelService()
		   .createJpqlQuery(jpql.toString())
		   .setParameters(conditionVals)
		   .setPage(currentPage, pageSize)
		   .pagedList();
		   
        return new Page<DailyRecordDTO>(pages.getStart(), pages.getResultCount(),pageSize, DailyRecordAssembler.toDTOs(pages.getData()));
	}

	
	@Override
	public InvokeResult getDepShow(DepShowDTO depShowDto) {
		String fromdate = DrgsIndex.formateDateFrom(depShowDto.getFromDate());
		String todate = DrgsIndex.formateDateTo(depShowDto.getToDate());
		String hospCode = depShowDto.getHospCode();
		String depCodes=depShowDto.getDepCodes();
		List<Map<String, Object>> resultMap = application.getDepShow(fromdate, todate,hospCode,depCodes);
		return InvokeResult.success(resultMap) ;
	}
	
	@Override
	public InvokeResult getDepOnlyShow(DepShowDTO depShowDto) {
		String fromdate = DrgsIndex.formateDateFrom(depShowDto.getFromDate());
		String todate = DrgsIndex.formateDateFrom(depShowDto.getToDate());
		String depCode = depShowDto.getDepCode();
		
		List<Map<String, Object>> resultMap = application.getDepOnlyShow(fromdate, todate,depCode);
		if(resultMap.size()<=0){
			String sql = "select a.dep_name ,depgroup_desc from DRGs.t_department a left join DRGs.t_depgroup b on a.pardepgroup_code = b.depgroup_code where a.dep_code = '"+depCode+"'";
			resultMap = jdbcTemplateObj.queryForList(sql);
		}
		return InvokeResult.success(resultMap) ;
	}
	
	@Override
	public InvokeResult getChangeDetail(DepShowDTO depShowDto) {
		String fromdate = DrgsIndex.formateDateFrom(depShowDto.getFromDate());
		String todate = DrgsIndex.formateDateTo(depShowDto.getToDate());
		String depName = depShowDto.getDepName();
		String type = depShowDto.getType();
		
		List<Map<String, Object>> resultMap = application.getChangeDetail(fromdate,todate,depName,type);
		return InvokeResult.success(resultMap) ;
	}
	
	@Override
	public InvokeResult getLastestIssue(DepShowDTO depShowDto) {
		String mrDate = application.getLastestIssue(depShowDto.getHospCode());
		return InvokeResult.success(mrDate) ;
	}
	/**
	 *  @Description：获取异常数据
	 *  @Author：liuhongjun 
	 *  @see com.dhcc.DRGsHosp.facade.DailyRecordFacade#getIsAbnormal(com.dhcc.DRGsHosp.facade.dto.DepShowDTO)
	 */
	@Override
	public InvokeResult  getIsAbnormal(DepShowDTO depShowDto){
		String fromDate = DrgsIndex.formateDateFrom(depShowDto.getFromDate());
		String toDate = DrgsIndex.formateDateFrom(depShowDto.getToDate());
		String hospCode = depShowDto.getHospCode();
		String depCodes=depShowDto.getDepCodes();
		int count = application.getIsAbnormal(fromDate, toDate,hospCode,depCodes);
		return InvokeResult.success(count) ;
	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DailyRecordFacade#saveOrUpdate(com.dhcc.DRGsHosp.facade.dto.DepShowDTO)
	 */
	@Override
	public InvokeResult saveOrUpdate(DepShowDTO dto){
		application.saveOrUpdate(dto.getDrOutDep(),dto.getDrIsAbnormal() , dto.getDrEpisodeId(),dto.getHospCode());		
		return InvokeResult.success();
	}

/**
 * 
 *  @Description：监测已有数据
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.DailyRecordFacade#daysDataImport()
 */
	@Override
	public InvokeResult daysDataImport(String wsUrl ,String method,String hospCode) {
		try {
			JaxWsDynamicClientFactory factory=JaxWsDynamicClientFactory.newInstance();
			factory.createClient(wsUrl);
		} catch (Exception e) {
			e.printStackTrace();
			return InvokeResult.failure("接口调用错误，请检查！");
		}
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Calendar calendar = Calendar.getInstance();
		Calendar cal = Calendar.getInstance();
		calendar.add(Calendar.DATE, -1);
		cal.add(Calendar.MONTH, -2);// 计算上个月
		cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));// 上个月的第一天
		String yesterday = dateFormat.format(calendar.getTime());// 昨天日期
		String lastMonth = dateFormat.format(cal.getTime());

		List<String> dayAllList = new ArrayList<String>();// 存储全日期List
		List<String> daysList = new ArrayList<String>();// 存储当前数据库中已有的日期List
		// 构建全日期的List
		while (calendar.compareTo(cal) >= 0) {
			dayAllList.add(dateFormat.format(cal.getTime()));
			System.out.println(cal.getTime());
			cal.add(Calendar.DATE, 1);
		}
		lastMonth = DrgsIndex.formateDateFrom(lastMonth);
		yesterday = DrgsIndex.formateDateTo(yesterday);
		List<String> haveDataDayList = application.haveDataDayList(yesterday, lastMonth,hospCode);
		if (!haveDataDayList.isEmpty()) {
			for (String outDate : haveDataDayList) {
				daysList.add(outDate);
			}
		}
		// 计算交集的差集
		List<String> tempDayAll = new ArrayList<String>();// excelDrg,drgList
		tempDayAll.addAll(dayAllList);
		tempDayAll.retainAll(daysList);// day对比交集大小
		dayAllList.removeAll(tempDayAll);// 交集的差集，差集为0，说明drg全能对上

		if (dayAllList.size() > 0) {
			for (int i = 0; i < dayAllList.size(); i++) {
				//daysParserXml((String) dayAllList.get(i),wsUrl,method);
				dayMonitorFacade.daysParserXml((String) dayAllList.get(i));
			}
		}
		return InvokeResult.success(dayAllList.size());
	}
	
//	/**
//     * @methodname    :daysParserXml
//     * @description   :根据传入的日期，解析xml ，存储DailyRecord
//     * @param         :str，传递过来的xml字符串 
//     * @author        :WangTeng
//     * @return        :
//     * @date          :2014年9月16日
//     * ----不使用下面方法了，使用
//     */
//	public void daysParserXml(String day, String wsUrl, String method) {
//
//		List<Department> depList = departmentApplication.findAllDepartment();
//		Map<String, String> depHisdep = new HashMap<>();// HIS科室名和本地库科室名map
//		for (Department dep : depList) {
//			if (!StringUtils.isEmpty(dep.getDepHis())) {
//				String[] deps = dep.getDepHis().split(",");
//				for (String his : deps) {
//					depHisdep.put(his, dep.getDepName());
//				}
//			}
//		}
//		String inHisDep = "";// 入院his科室
//		String outHisDep = "";// 出院his科室
//		Logger logger = LoggerFactory.getLogger(DailyRecordFacadeImpl.class);
//		PropertyConfigurator.configure(DailyRecordFacadeImpl.class.getResource("/dailyLog.properties"));
//		int successNum = 0;
//		int totalNum = 0;
//		try {
//			// 动态调用
//			JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
//			org.apache.cxf.endpoint.Client client = factory.createClient(wsUrl);
//			// 日期格式
//			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
//			Object[] objects = client.invoke(method, day);
//			String xml = (String) objects[0];// xml字符串
//			// 替换xml里的“--@%Library.GlobalCharacterStream”
//			xml = xml.replaceAll("\\d\\d@%Library.GlobalCharacterStream", "");
//
//			StringReader read = new StringReader(xml);
//			// 创建新的输入源SAX 解析器将使用 InputSource 对象来确定如何读取 XML 输入
//			InputSource source = new InputSource(read);
//			// 创建一个新的SAXBuilder
//			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//			DocumentBuilder db = dbf.newDocumentBuilder();
//			Document document = db.parse(source);
//			// 根节点
//			Node rootNode = document.getChildNodes().item(0);
//			NodeList nodeList = rootNode.getChildNodes();
//			totalNum = nodeList.getLength();
//			for (int i = 0; i < nodeList.getLength(); i++) {
//				Node node = nodeList.item(i);
//				if (node.getNodeType() != Node.ELEMENT_NODE) {
//					continue;
//				}
//				DailyRecord dailyRecord = new DailyRecord();
//				for (int j = 0; j < node.getChildNodes().getLength(); j++) {
//					// 获取子节点
//					Node childNode = node.getChildNodes().item(j);
//					if (childNode.getNodeType() != Node.ELEMENT_NODE || !childNode.hasChildNodes()) {
//						continue;
//					}
//					// 节点名
//					String nodeName = childNode.getNodeName();
//					// 节点值
//					String nodeValue = childNode.getFirstChild().getNodeValue();
//					// 循环子节点
//					if (childNode.getNodeType() == Node.ELEMENT_NODE) {
//						if ("PatientID".equals(nodeName)) {
//							// 病案号---其实是登记号
//							// dailyRecord.setDrMrNo(nodeValue);
//						} else if ("PatientNo".equals(nodeName)) {
//							// 登记号---其实是病案号
//							System.out.println("登记号：" + nodeValue);
//							dailyRecord.setDr_mr_no(nodeValue);
//						} else if ("ADMRowid".equals(nodeName)) {
//							// 就诊ID
//							dailyRecord.setDr_episode_id(nodeValue);
//							//dailyRecord.setDrEpisodeid(nodeValue);
//						} else if ("PatientName".equals(nodeName)) {
//							// 病人姓名
//							dailyRecord.setDr_patient_name(nodeValue);
//						} else if ("SocialStatus".equals(nodeName)) {
//							// 病人类型
//							dailyRecord.setDr_patient_type(nodeValue);
//						} else if ("RDesc".equals(nodeName)) {
//							// 入院his科室
//							dailyRecord.setDr_in_hisdep(nodeValue);
//							dailyRecord.setDr_in_dep(nodeValue);
//							inHisDep = nodeValue;
//						} else if ("PatDep".equals(nodeName)) {
//							// 出院his科室
//							dailyRecord.setDr_out_hisdep(nodeValue);
//							dailyRecord.setDr_out_dep(nodeValue);
//							outHisDep = nodeValue;
//						} else if ("AdmDate".equals(nodeName)) {
//							// 入院日期
//							dailyRecord.setDr_in_date(dateFormat.parse(nodeValue));
//						} else if ("DischDate".equals(nodeName)) {
//							// 出院日期
//							dailyRecord.setDr_out_date(dateFormat.parse(nodeValue));
//						} else if ("AllOrdFee".equals(nodeName)) {
//							// 总费用
//							dailyRecord.setDr_total_cost(Double.valueOf(nodeValue));
//						} else if ("DrugOrdFee".equals(nodeName)) {
//							// 药品费用
//							dailyRecord.setDr_drug_cost(Double.valueOf(nodeValue));
//						} else if ("QTOrdFee".equals(nodeName)) {
//							// 非药品费用
//							dailyRecord.setDr_nodrug_cost(Double.valueOf(nodeValue));
//						} else if ("AdmDocName".equals(nodeName)) {
//							// 主治医师
//							dailyRecord.setDr_protoMedicus(nodeValue);
//						} else if ("AdmDocGP".equals(nodeName)) {
//							// 主诊医师
//							dailyRecord.setDr_group_name(nodeValue);
//						}
//					}
//				}
//				// 修改PICU为小儿心脏科
//				if (inHisDep.equals("PICU")) {
//					dailyRecord.setDr_in_dep("小儿心脏科");
//				}
//				if (outHisDep.equals("PICU")) {
//					dailyRecord.setDr_out_dep("小儿心脏科");
//				}
//				// 修改PICU为小儿心脏科
//				if (inHisDep.equals("picu")) {
//					dailyRecord.setDr_in_dep("小儿心脏科");
//				}
//				if (outHisDep.equals("picu")) {
//					dailyRecord.setDr_out_dep("小儿心脏科");
//				}
//				// 判断是否异常
//				String inDep = depHisdep.get(dailyRecord.getDr_in_dep());
//				String outDep = depHisdep.get(dailyRecord.getDr_out_dep());
//				// 修改科室名
//				if (inDep != null && outDep != null) {
//					// 出入院都正常，标为正常
//					dailyRecord.setDr_in_dep(inDep);
//					dailyRecord.setDr_out_dep(outDep);
//					dailyRecord.setDr_is_abnormal((double) 0);
//				} else if (inDep != null && outDep == null) {
//					dailyRecord.setDr_in_dep(inDep);
//					if (outHisDep.equals("sicu") || outHisDep.equals("ICU") || outHisDep.equals("icu")
//							|| outHisDep.equals("SICU")) {
//						// 入院正常，出院为sicu和ICU时，将出院科室改为入院科室，标为正常
//						dailyRecord.setDr_out_dep(dailyRecord.getDr_in_dep());
//						dailyRecord.setDr_is_abnormal((double) 0);
//					} else if (outHisDep.equals("妇产科") || outHisDep.equals("综合科")) {
//						// 入院正常，出院为妇产科和综合科时，标为正常
//						dailyRecord.setDr_is_abnormal((double) 0);
//					} else {
//						// 其余入院正常，出院异常的全部标为异常
//						dailyRecord.setDr_is_abnormal((double) 1);
//					}
//				} else if (inDep == null && outDep != null) {
//					dailyRecord.setDr_out_dep(outDep);
//					if (inHisDep.equals("妇产科") || inHisDep.equals("综合科")) {
//						// 出院正常，入院为妇产科和综合科时，标为正常
//						dailyRecord.setDr_is_abnormal((double) 0);
//					} else {
//						// 其余出院正常，入院异常的全部标为异常
//						dailyRecord.setDr_is_abnormal((double) 1);
//					}
//				} else {
//					if (outHisDep.equals("妇产科") && inHisDep.equals("妇产科")) {
//						// 出入院都为妇产科是标为正常
//						dailyRecord.setDr_is_abnormal((double) 0);
//					} else if (outHisDep.equals("综合科") && inHisDep.equals("综合科")) {
//						// 出入院都为综合科是标为正常
//						dailyRecord.setDr_is_abnormal((double) 0);
//					} else {
//						// 出入院都异常的标为异常
//						dailyRecord.setDr_is_abnormal((double) 1);
//					}
//
//				}
//				// 存储
//				try {
//					application.creatDailyRecord(dailyRecord);
//				} catch (Exception e) {
//					logger.error("【保存时报错，" + e.getMessage() + "】" + "就诊ID：" + dailyRecord.getDr_episode_id() + "，病案号："
//							+ dailyRecord.getDr_mr_no() + "，姓名：" + dailyRecord.getDr_patient_name());
//					continue;
//				}
//				successNum++;
//			}
//
//			logger.info("总共：" + totalNum + "，保存成功：" + successNum);
//		} catch (Exception e) {
//			System.out.println(e.getMessage());
//			logger.error("总共：" + totalNum + "，保存成功：" + successNum + "。" + e.getMessage());
//		}
//	}

	/* (non-Javadoc)
	 * @see com.dhcc.DRGsHosp.facade.DailyRecordFacade#sendMessage(com.dhcc.DRGsHosp.facade.dto.DepShowDTO)
	 */
	@Override
	public InvokeResult sendMessage(DepShowDTO depShowDto) {
		String message = depShowDto.getMessage();
		System.out.println("message:"+message);
		
		//用来最后拼接反馈给前台信息的
		 String rnInfo="发送已完成.";
		 
		//查询累计日期，用来在反馈信息中提示累计数据到几月的
		String accDate = "";
		String MCDate = accDate.substring(0,7);

		//查询科室信息,拼接科室map，用来查找科室电话或者科室名称
		List<Department> depList = departmentApplication.findAllDepartment();
		Map<String, String> depFindTelMap = new HashMap<String, String>();//科室名称代码信息
		Map<String, String> depFindNameMap = new HashMap<String, String>();//科室名称代码信息
		
		for (Department dep : depList) {
			depFindTelMap.put(dep.getDepName(), dep.getDepTelephone());
			depFindNameMap.put(dep.getDepTelephone(), dep.getDepName());
		}
		
		//将信息参数根据分隔符处理成多条数据，每条数据是一个科室的信息
	//	Map<String, String> mapMessage=new HashMap();
		List<DepShowDTO> messageList=new ArrayList<DepShowDTO>();
		String[] tempDep = message.split(";");
		System.out.println("分隔后的数组："+Arrays.toString(tempDep));
		
		int depNum=tempDep.length;//一共发送的信息数量
		
		//循环处理信息数据
		for(int i=0;i<tempDep.length;i++){
			System.out.println("第"+i+"条处理信息："+tempDep[i]);
			//tempDep[i]='心内一','2015-01-01':'2015-01-01':'36120','180','28538.54','29093.5','0','0'
			String[] tempMes=tempDep[i].split(":");
			
			String depName = "";
			String depNameRe = "";//depName-是为了处理妇产科、综合科的，depNameRe-是为了反馈信息里的科室名的
			String fromDate = "";
			String toDate = "";
			String bavgcost="";
			String outsum="";
			String avgcost="";
			String accavgcost="";
			String curstand="";
			String accstand="";
			
			 depName = tempMes[0];
			 depNameRe = depName;//depName-是为了处理妇产科、综合科的，depNameRe-是为了反馈信息里的科室名的
			 fromDate = tempMes[1];
			 toDate = tempMes[2];
			 bavgcost=tempMes[3];
			 outsum=tempMes[4];
			 avgcost=tempMes[5];
			 accavgcost=tempMes[6];
			 curstand=tempMes[7];
			 accstand=tempMes[8];
			System.out.println("每个信息的每个信息："+depName+"~"
			 +fromDate+"~"+toDate+"~"+bavgcost+"~"+outsum+"~"+avgcost+"~"+accavgcost+"~"+curstand+"~"+accstand);
			
			String reInfo=null;
			
			//处理妇产科、综合科科室名称
			if(depName.equals("妇产科")){
				depName="妇科";
			}else if(depName.equals("综合科")){
				depName="综合科十七";
			}
				
			float curstandInt = Float.parseFloat(curstand);
			System.out.println("是否达标："+curstandInt);
			String curInfo=null;
			
			//拼凑反馈信息
			{
				if(curstandInt>0){
					curInfo="未达标";
				}else{
					curInfo="已达标";
				}
				
				 reInfo="尊敬的"+depNameRe+"科领导"+",您好。科室次均费用目标值为"+bavgcost+"元，科室截止"+MCDate+"累计次均费用为"+accavgcost+
						"。"+fromDate+"日至"+toDate+
						"日，出院人数为："+outsum+"，次均费用为："+avgcost+" "+curInfo+"<br>感谢贵科室对医保办的支持！如需我们帮助，随时联系";
				 System.out.println(reInfo);
			}
			
			//查找科室电话号码，注意使用处理后的科室名称
			String phone=depFindTelMap.get(depName);
			System.out.println("科室名称和电话"+depName+":"+phone);
		//	mapMessage.put(phone, reInfo);
			DepShowDTO dto=new DepShowDTO();
			dto.setDepName(depNameRe);
			dto.setDepPhone(phone);
			dto.setMessage(reInfo);
			messageList.add(dto);
		}
		return InvokeResult.success(messageList);
	}

	
/**
 * 
 *  @Description：病例日监测
 *  @Author LiuHongJun  
 *  @see com.dhcc.DRGsHosp.facade.DailyRecordFacade#findDailyRecordInterFace()
 */
	@Override
	public InvokeResult findDailyRecordInterFace() {
		String dayMonitor=GlobalData.sysConfig.get("DAY_MONITOR");
		Map<String,Object> map=new HashMap<>();
		if(StringUtils.hasLength(dayMonitor)&&dayMonitor.split("θ").length==2){
			String wsUrl = dayMonitor.split("θ")[0];
		    String 	method = dayMonitor.split("θ")[1];
		    map.put("wsUrl", wsUrl);
		    map.put("method", method);
		    return InvokeResult.success(map);
		}else{
			return InvokeResult.failure("请先在系统配置里配置日监测接口！");
		}
	}

    /**
     * 
     *  @Description：查询异常日监测数据
     *  @Author LiuHongJun  
     *  @see com.dhcc.DRGsHosp.facade.FileUploadFacade#findDailyRecords()
     */
	@Override
	public List<DailyRecordDTO> findDailyRecords(DepShowDTO depShowDto) {
		String hospCode = depShowDto.getHospCode();
		List<DailyRecordDTO> drDTOList = new ArrayList<DailyRecordDTO>();
		List<Object[]> drList =  application.findDailyRecords(hospCode);
		for (Object[] obj : drList) {
		//	DailyRecordDTO drDTO = DailyRecordAssembler.toDTO(dailyRecord);
			DailyRecordDTO drDTO = new DailyRecordDTO();
			drDTO.setDrEpisodeid(obj[0]==null?"":obj[0].toString());
			drDTO.setDrMrno(obj[1]==null?"":obj[1].toString());
			drDTO.setDrPatientname(obj[2]==null?"":obj[2].toString());
			drDTO.setDrPatienttype(obj[3]==null?"":obj[3].toString());
			drDTO.setDrInhisdep(obj[4]==null?"":obj[4].toString());
			drDTO.setDrOuthisdep(obj[5]==null?"":obj[5].toString());		
			try {
				drDTO.setDrOutdate((Date) (obj[6]==null?"":new SimpleDateFormat("yyyy-MM-dd").parse(obj[6].toString())));
			} catch (ParseException e) {
				e.printStackTrace();
			}
			drDTO.setDrIsabnormal((Double) (obj[7]==null?"":Double.parseDouble(obj[7].toString())));
			drDTOList.add(drDTO);
		}
		return drDTOList;
	}
    	
	@Override
	public InvokeResult getDepWeekData(DepShowDTO depShowDto) {
		String fromdate = DrgsIndex.formateDateFrom(depShowDto.getFromDate());
		String todate = DrgsIndex.formateDateTo(depShowDto.getToDate());
		String hospCode = depShowDto.getHospCode();
		String depCodes = CurrentUser.getDeps()	;
		IndexCalDTO dto = new IndexCalDTO();
		dto.setDateFrom(fromdate);
		dto.setDateTo(todate);
		dto.setHospCode(hospCode);
		Department d = new Department(depCodes);
		List<Map<String, Object>> deps = departmentApplication.findDepNamesByDepCodes(depCodes);
		String depNames = "";
		for(Map<String, Object> dep: deps){
			depNames += dep.get("DEP_NAME")+",";
		}
		if(depNames.contains(",")){
			depNames = depNames.substring(0, depNames.length()-1);
		}
		dto.setDeps(depNames);//此处将科室代码转换为科室名称
		dto.setUseBaseQuota("0");
		dto.setMonitorType("hosp");
		dto.setQuotaCode("DRAvgFee,DRTotalCaseCnt,DRAvgDays,DRDrugRatio");
		dto.setIsGetCc("only2");
		List<Map<String, Object>> hospQuotaList = drgsIndexCalFacade.indexCal(dto);
		
		dto.setMonitorType("dep");
		dto.setQuotaCode("DRAvgFee,DRTotalCaseCnt,DRAvgDays,DRDrugRatio,DRDepInCaseCnt,DRDepOutCaseCnt,DRExcessCnt_F");
		List<Map<String, Object>> depQuotaList = drgsIndexCalFacade.indexCal(dto);
		//单独计算费用未超标患者数, 总人数-费用超标人数
		for(Map<String, Object> m: depQuotaList){
			Object drTotalCaseCnt = m.get("DRTotalCaseCnt");
			Object drExcessCntf = m.get("DRExcessCnt_F");
			Double c1 = drTotalCaseCnt!=null?Double.valueOf(drTotalCaseCnt.toString()):0;
			Double c2 = drExcessCntf!=null?Double.valueOf(drExcessCntf.toString()):0;
			double c = c1 -c2;
			m.put("NDRExcessCnt_F", c);
		}
		Map<String, Map<String, Object>> result = new LinkedHashMap<>();
		for(Map<String, Object> m: depQuotaList){
			if(m.get("ddesc")!=null){
				result.put(m.get("ddesc").toString(), m);
			}
		}
		
		//获取目标值
		dto.setQuotaCode("DRAvgFeeCC,DRAvgDaysCC,DRDrugRatioCC");
		List<Map<String, Object>> depQuotaCCList = drgsIndexCalFacade.indexCal(dto);
		for(Map<String, Object> m: depQuotaCCList){
			if(m.get("ddesc")!=null){
				String key = m.get("ddesc").toString();
				if(result.containsKey(key)){
					for(Entry<String, Object> entry: m.entrySet()){
						result.get(key).put(entry.getKey(), entry.getValue());
					}
				}
			}
		}
		
		//获取累积值
		dto.setDeps(depCodes);//此处使用科室代码,累计值查询的是首页表
		String fromdate_s = fromdate.substring(0, 4)+"-01-01";
		dto.setDateFrom(fromdate_s);
		dto.setQuotaCode("DRAvgFeeMC,DRTotalCaseCntMC,DRAvgDaysMC,DRDrugRatioMC");
		List<Map<String, Object>> depQuotaMCList = drgsIndexCalFacade.indexCal(dto);
		for(Map<String, Object> m: depQuotaMCList){
			if(m.get("ddesc")!=null){
				String key = m.get("ddesc").toString();
				if(result.containsKey(key)){
					for(Entry<String, Object> entry: m.entrySet()){
						result.get(key).put(entry.getKey(), entry.getValue());
					}
				}
			}
		}
		
		//获取同期累积值
		String fromdate_ss = DrgsIndex.getDateFromCc(fromdate_s, "year");
		String todate_ss = DrgsIndex.getDateFromCc(todate, "year");
		dto.setDateFrom(fromdate_ss);
		dto.setDateTo(todate_ss);
		dto.setQuotaCode("DRAvgFeeMC");
		List<Map<String, Object>> depQuotaSSMCList = drgsIndexCalFacade.indexCal(dto);
		for(Map<String, Object> m: depQuotaSSMCList){
			if(m.get("ddesc")!=null){
				String key = m.get("ddesc").toString();
				if(result.containsKey(key)){
					for(Entry<String, Object> entry: m.entrySet()){
						result.get(key).put(entry.getKey()+"C", entry.getValue());
					}
				}
			}
		}

		List<Map<String, Object>> resultList = new LinkedList<>();
		//获取全院监测值
		if(hospQuotaList.size()>0){
			Map<String, Object> hosp = hospQuotaList.get(0);
			Object objDRAvgFee = hosp.get("DRAvgFee");//次均费用
			Object objDRAvgDays = hosp.get("DRAvgDays");//平均住院日
			Object objDRTotalCaseCnt = hosp.get("DRTotalCaseCnt");//出院人次
			Object objDRDrugRatio = hosp.get("DRDrugRatio");//药占比
			Map<String, Object> resultHosp = new HashMap<>();
			resultHosp.put("OUTSUM", objDRTotalCaseCnt);
			resultHosp.put("AVGCOST", objDRAvgFee);
			resultHosp.put("AVGBEDDAYS", objDRAvgDays);
			resultHosp.put("DRUGRATIO", objDRDrugRatio);
			resultList.add(resultHosp);
		}
		for(Entry<String, Map<String, Object>> entry: result.entrySet()){
			Map<String, Object> objDep = entry.getValue();
			Object objDepName = objDep.get("ddesc");
			Object objDRAvgFee = objDep.get("DRAvgFee");//次均费用
			Object objDRAvgDays = objDep.get("DRAvgDays");//平均住院日
			Object objDRTotalCaseCnt = objDep.get("DRTotalCaseCnt");//出院人次
			Object objDRDrugRatio = objDep.get("DRDrugRatio");//药占比
			Object objDRAvgFeeMC = objDep.get("DRAvgFeeMC");//次均费用累计值
			Object objDRAvgDaysMC = objDep.get("DRAvgDaysMC");//平均住院日累计值
			Object objDRTotalCaseCntMC = objDep.get("DRTotalCaseCntMC");//人数累计值
			Object objDRDrugRatioMC = objDep.get("DRDrugRatioMC");//药占比累计值
			Object objDRAvgFeeMCC = objDep.get("QuotaValueC");//次均费用同期累计值
			Object objDRAvgFeeCC = objDep.get("DRAvgFeeCC");//次均费用目标值
			Object objDRAvgDaysCC = objDep.get("DRAvgDaysCC");//平均住院日目标值
			Object objDRDrugRatioCC = objDep.get("DRDrugRatioCC");//药占比目标值
			Object objDRDepInCaseCnt = objDep.get("DRDepInCaseCnt");//转入人数
			Object objDRDepOutCaseCnt = objDep.get("DRDepInCaseCnt");//转出人数
			Object objDRExcessCnt_F = objDep.get("DRExcessCnt_F");//费用超标人数
			Object objNDRExcessCnt_F = objDep.get("NDRExcessCnt_F");//费用未超标人数
			//重新进行组装
			Map<String, Object> resultDep = new HashMap<>();
			resultDep.put("DR_OUT_DEP", objDepName);
			resultDep.put("AVGCOST", objDRAvgFee);
			resultDep.put("BAVGCOST", objDRAvgFeeCC);
			resultDep.put("SUM_AVGCOST", objDRAvgFeeMC);
			resultDep.put("QUOTA_DETAIL_SUM", objDRAvgFeeMCC);
			resultDep.put("OVERBENCHMARK", objDRExcessCnt_F);
			resultDep.put("NOTOVER", objNDRExcessCnt_F);
			resultDep.put("DEPIN", objDRDepInCaseCnt);
			resultDep.put("DEPOUT", objDRDepOutCaseCnt);
			resultDep.put("OUTSUM", objDRTotalCaseCnt);
			resultDep.put("SUM_OUTSUM", objDRTotalCaseCntMC);
			resultDep.put("AVGBEDDAYS", objDRAvgDays);
			resultDep.put("BAVGDAYS", objDRAvgDaysCC);
			resultDep.put("SUM_AVGBEDDAYS", objDRAvgDaysMC);
			resultDep.put("DRUGRATIO", objDRDrugRatio);
			resultDep.put("BDRUGCOSTRATIO", objDRDrugRatioCC);
			resultDep.put("SUM_DRUGRATION", objDRDrugRatioMC);
			resultList.add(resultDep);
		}
		
//    		List<Map<String, Object>> resultMap = application.getDepWeekData(fromdate, todate,hospCode,depCodes);
		return InvokeResult.success(resultList) ;
	}
}
